package com.atguigu.gulimall.coupon.product.service.impl;

import com.atguigu.gulimall.coupon.product.dao.CategoryDao;
import com.atguigu.gulimall.coupon.product.entity.CategoryEntity;
import com.atguigu.gulimall.coupon.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        List<CategoryEntity> treeList = categoryEntityList.stream().filter(categoryEntity -> categoryEntity.getCatLevel() == 1).
                map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity,categoryEntityList));
                    return categoryEntity;
                }).sorted(Comparator.comparing((CategoryEntity::getSort)).thenComparing(CategoryEntity::getSort).thenComparingInt(CategoryEntity::getSort)).
                collect(Collectors.toList());
        return treeList;
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        //TODO 判断是否被其他地方引用
        baseMapper.deleteBatchIds(asList);
    }

    private List<CategoryEntity> getChildrens(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntityList) {
        List<CategoryEntity> entities = categoryEntityList.stream().
                filter(category -> category.getParentCid().intValue() == categoryEntity.getCatId().intValue()).
                map(category -> {
                    category.setChildren(getChildrens(category, categoryEntityList));
                    return category;
                }).
                sorted(Comparator.comparing((CategoryEntity::getSort)).thenComparing(CategoryEntity::getSort).thenComparingInt(CategoryEntity::getSort)).
                collect(Collectors.toList());
        return entities;
    }

}